import {getAddressList, getCode, getLogout, postLogin, postRegister,putUserDefaultAddressById} from "@/api/user";

export default {
    namespaced:true,
    state:{
        userInfo:{},
        addressList:[]
    },
    mutations:{
        SET_USER_INFO(state,payload){
            state.userInfo = payload;
            localStorage.setItem('token',payload.token);
        },
        SET_LOG_OUT(state){
            state.userInfo = {};
            localStorage.removeItem('token');
        },
        SET_ADDRESS_LIST(state,payload){
            state.addressList = payload;
        }
    },
    actions:{
        async postRegisterAsync(_,payload){
            await postRegister(payload);
        },
        async getCodeAsync(_,phone){
            const response = await getCode(phone);
            return response.data;
        },
        async postLoginAsync({commit},{phone,password}){
            const response = await postLogin(phone,password);
            commit('SET_USER_INFO',response.data);
        },
        async getLogout({commit}){
            await getLogout();
            commit('SET_LOG_OUT');
        },
        async getAddressListAsync({commit}){
            const response = await getAddressList();
            commit('SET_ADDRESS_LIST',response.data);
        },
        async putUserDefaultAddressByIdAsync({dispatch,commit},id){
            await putUserDefaultAddressById(id);
            // 如果数据可以让多个用户同时操作。建议使用第1个。
            // 1-
            dispatch("getAddressListAsync");
            // 2
            // commit("UP_ADDRESS_BY_ID",id);

        }
    },
}